<template>
  <span :data-text="displayValue">
    {{ displayValue }}
  </span>
</template>
<script>
import {
  requestAnimationFrame,
  cancelAnimationFrame,
} from "./requestAnimationFrame.js";

export default defineComponent({
  name: "countTo",
  props: {
    startVal: {
      type: Number,
      required: false,
      default: 0,
    },
    endVal: {
      type: Number,
      required: false,
      default: 2017,
    },
    duration: {
      type: Number,
      required: false,
      default: 3000,
    },
    autoplay: {
      type: Boolean,
      required: false,
      default: true,
    },
    decimals: {
      type: Number,
      required: false,
      default: 0,
      validator(value) {
        return value >= 0;
      },
    },
    decimal: {
      type: String,
      required: false,
      default: ".",
    },
    separator: {
      type: String,
      required: false,
      default: ",",
    },
    prefix: {
      type: String,
      required: false,
      default: "",
    },
    suffix: {
      type: String,
      required: false,
      default: "",
    },
    useEasing: {
      type: Boolean,
      required: false,
      default: true,
    },
    easingFn: {
      type: Function,
      default(t, b, c, d) {
        return (c * (-Math.pow(2, (-10 * t) / d) + 1) * 1024) / 1023 + b;
      },
    },
  },
  emits: ["callback", "mountedCallback"],
  setup(props, { emit }) {
    const pageData = reactive({
      localStartVal: props.startVal,
      printVal: null,
      paused: false,
      localDuration: props.duration,
      startTime: null,
      timestamp: null,
      remaining: null,
      rAF: null,
    });

    const count = function (timestamp) {
      if (!pageData.startTime) pageData.startTime = timestamp;
      pageData.timestamp = timestamp;
      const progress = timestamp - pageData.startTime;
      pageData.remaining = pageData.localDuration - progress;

      if (props.useEasing) {
        if (countDown.value) {
          pageData.printVal =
            pageData.localStartVal -
            props.easingFn(
              progress,
              0,
              pageData.localStartVal - props.endVal,
              pageData.localDuration
            );
        } else {
          pageData.printVal = props.easingFn(
            progress,
            pageData.localStartVal,
            props.endVal - pageData.localStartVal,
            pageData.localDuration
          );
        }
      } else {
        if (countDown.value) {
          pageData.printVal =
            pageData.localStartVal -
            (pageData.localStartVal - props.endVal) *
              (progress / pageData.localDuration);
        } else {
          pageData.printVal =
            pageData.localStartVal +
            (props.endVal - pageData.localStartVal) *
              (progress / pageData.localDuration);
        }
      }
      if (countDown.value) {
        pageData.printVal =
          pageData.printVal < props.endVal ? props.endVal : pageData.printVal;
      } else {
        pageData.printVal =
          pageData.printVal > props.endVal ? props.endVal : pageData.printVal;
      }

      nextTick(() => {
        displayValue.value = formatNumber(pageData.printVal);
      });
      if (progress < pageData.localDuration) {
        pageData.rAF = requestAnimationFrame(count);
      } else {
        emit("callback");
      }
    };

    const start = function () {
      pageData.localStartVal = props.startVal;
      pageData.startTime = null;
      pageData.localDuration = props.duration;
      pageData.paused = false;
      pageData.rAF = requestAnimationFrame(count);
    };
    const pauseResume = function () {
      if (pageData.paused) {
        resume();
        pageData.paused = false;
      } else {
        pause();
        pageData.paused = true;
      }
    };
    const pause = function () {
      cancelAnimationFrame(pageData.rAF);
    };
    const resume = function () {
      pageData.startTime = null;
      pageData.localDuration = +pageData.remaining;
      pageData.localStartVal = +pageData.printVal;
      requestAnimationFrame(count);
    };
    const reset = function () {
      pageData.startTime = null;
      cancelAnimationFrame(pageData.rAF);
      displayValue.value = formatNumber(props.startVal);
    };

    const isNumber = function (val) {
      return !isNaN(parseFloat(val));
    };
    const formatNumber = function (num) {
      num = Number(num).toFixed(props.decimals);
      num += "";
      const x = num.split(".");
      let x1 = x[0];
      const x2 = x.length > 1 ? props.decimal + x[1] : "";
      const rgx = /(\d+)(\d{3})/;
      if (props.separator && !isNumber(props.separator)) {
        while (rgx.test(x1)) {
          x1 = x1.replace(rgx, "$1" + props.separator + "$2");
        }
      }
      return props.prefix + x1 + x2 + props.suffix;
    };

    const displayValue = ref(formatNumber(props.startVal));
    const countDown = computed(() => {
      return props.startVal > props.endVal;
    });

    watch(
      () => props.startVal,
      () => {
        if (props.autoplay) {
          start();
        }
      }
    );

    watch(
      () => props.endVal,
      () => {
        if (props.autoplay) {
          start();
        }
      }
    );

    onMounted(() => {
      if (props.autoplay) {
        start();
      }
      emit("mountedCallback");
    });
    onBeforeUnmount(() => {
      cancelAnimationFrame(pageData.rAF);
    });

    return {
      displayValue,
    };
  },
});
</script>
